/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewChangeUnitForm_ColumnList.java
 *
 * Created on Mar 8, 2010, 10:03:34 AM
 */

package operator;

import java.awt.List;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;

import mechanic.ChangeUnit;

import client.Client;

import util.Pair;

/**
 * 
 * @author jc.deoferio
 */
public class NewChangeUnitForm_ColumnList extends javax.swing.JFrame {

	/** Creates new form NewChangeUnitForm_ColumnList */
	public NewChangeUnitForm_ColumnList() {
		initComponents();
	}

	private Client c;
	private String[] tableNames;
	private LinkedList<ChangeUnit> changeUnits;
	private NewChangeUnitForm_TableList tableList;

	public NewChangeUnitForm_ColumnList(Object[] tablenames, Client c, NewChangeUnitForm_TableList newChangeUnitFormTableList)
			throws SQLException {
		tableNames = new String[tablenames.length];
		tableList = newChangeUnitFormTableList;
		for(int i=0;i<tablenames.length;i++){
			tableNames[i] = tablenames[i].toString();
		}
		this.c = c;
		initComponents();
		initComponents2();
	}

	private void initComponents2() throws SQLException {
		setLocationRelativeTo(null);
		// selectedList.setModel(new javax.swing.AbstractListModel() {
		// String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5"
		// };
		// public int getSize() { return strings.length; }
		// public Object getElementAt(int i) { return strings[i]; }
		// });
		//    	
		// unselectedList.setModel(new javax.swing.AbstractListModel() {
		// String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5"
		// };
		// public int getSize() { return strings.length; }
		// public Object getElementAt(int i) { return strings[i]; }
		// });
		//    	
		// changeUnitList.setModel(new javax.swing.AbstractListModel() {
		// String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5"
		// };
		// public int getSize() { return strings.length; }
		// public Object getElementAt(int i) { return strings[i]; }
		// });

		LinkedList<String> columns = new LinkedList<String>();
		for(String tableName : tableNames){
			String cols[] = c.db.getColumns(tableName);
			for(String col:cols){
				columns.add(tableName+" "+col);
			}
		}

		for (String column : columns)
			unselectedList.add(column);
		changeUnits = new LinkedList<ChangeUnit>();
		
		changeUnitList.setModel(new AbstractListModel() {
			public int getSize() {
				return changeUnits.size();
			}
			
			public Object getElementAt(int arg0) {	
				return changeUnits.get(arg0).toString();
			}
		});
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jScrollPane2 = new javax.swing.JScrollPane();
		selectedList = new java.awt.List();
		Select = new javax.swing.JButton();
		Deselect = new javax.swing.JButton();
		jScrollPane3 = new javax.swing.JScrollPane();
		changeUnitList = new javax.swing.JList();
		jLabel1 = new javax.swing.JLabel();
		jScrollPane4 = new javax.swing.JScrollPane();
		unselectedList = new java.awt.List();
		createChangeUnit = new javax.swing.JButton();
		doneButton = new javax.swing.JButton();
		deleteChangeUnit = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jScrollPane2.setViewportView(selectedList);

		Select.setText(">>");
		Select.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				SelectActionPerformed(evt);
			}
		});

		Deselect.setText("<<");
		Deselect.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				DeselectActionPerformed(evt);
			}
		});

		jScrollPane3.setViewportView(changeUnitList);

		jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
		jLabel1.setText("Select Columns to add to a ChangeUnit");

		jScrollPane4.setViewportView(unselectedList);

		createChangeUnit.setText("Create");
		createChangeUnit.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				createChangeUnitActionPerformed(evt);
			}
		});

		doneButton.setText("Done");
		doneButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				doneButtonActionPerformed(evt);
			}
		});

		deleteChangeUnit.setText("Delete");
		deleteChangeUnit.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				deleteChangeUnitActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addComponent(
																								jScrollPane3,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								380,
																								Short.MAX_VALUE)
																						.addGroup(
																								javax.swing.GroupLayout.Alignment.TRAILING,
																								layout
																										.createSequentialGroup()
																										.addGap(
																												135,
																												135,
																												135)
																										.addComponent(
																												Select)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												Deselect)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																												72,
																												Short.MAX_VALUE)
																										.addComponent(
																												createChangeUnit))
																						.addComponent(
																								jLabel1)))
														.addGroup(
																javax.swing.GroupLayout.Alignment.TRAILING,
																layout
																		.createSequentialGroup()
																		.addGap(
																				8,
																				8,
																				8)
																		.addComponent(
																				jScrollPane4,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				186,
																				Short.MAX_VALUE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jScrollPane2,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				186,
																				Short.MAX_VALUE))
														.addGroup(
																javax.swing.GroupLayout.Alignment.TRAILING,
																layout
																		.createSequentialGroup()
																		.addContainerGap(
																				264,
																				Short.MAX_VALUE)
																		.addComponent(
																				deleteChangeUnit)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				doneButton)))
										.addContainerGap()));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(jLabel1)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																jScrollPane2,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																174,
																Short.MAX_VALUE)
														.addComponent(
																jScrollPane4,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																174,
																Short.MAX_VALUE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																createChangeUnit)
														.addComponent(Deselect)
														.addComponent(Select))
										.addGap(12, 12, 12)
										.addComponent(
												jScrollPane3,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												93,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																doneButton)
														.addComponent(
																deleteChangeUnit))
										.addGap(11, 11, 11)));

		pack();
	}// </editor-fold>

	private void SelectActionPerformed(java.awt.event.ActionEvent evt) {
		int idx = unselectedList.getSelectedIndex();
		if(idx < 0)
			return;
		String selectedColumn = unselectedList.getSelectedItem();
		unselectedList.remove(idx);
		selectedList.add(selectedColumn);
	}

	private void DeselectActionPerformed(java.awt.event.ActionEvent evt) {
		int idx = selectedList.getSelectedIndex();
		if(idx < 0)
			return;
		String selectedColumn = selectedList.getSelectedItem();
		selectedList.remove(idx);
		unselectedList.add(selectedColumn);
	}

	private void createChangeUnitActionPerformed(java.awt.event.ActionEvent evt){
		if(selectedList.getItemCount() <= 0)
			return;
		String[] tb_columns = selectedList.getItems();
		LinkedList<Pair<String,String>> attrEntries = new LinkedList<Pair<String,String>>();
		HashSet<String> tables = new HashSet<String>();
		
		for(String tb_col : tb_columns){
			String[] p = tb_col.split(" "); 
			attrEntries.add(new Pair<String, String>(p[0], p[1]));
			tables.add(p[0]);
		}
		
		try {
			ChangeUnit cu = c.db.newChangeUnit(tables.toString(), attrEntries);
			changeUnits.addLast(cu);
			changeUnitList.repaint();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {
		for(ChangeUnit cu : changeUnits)
			try {
				cu.saveToDB();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		setVisible(false);
		tableList.setVisible(true);
	}

	private void deleteChangeUnitActionPerformed(java.awt.event.ActionEvent evt) {
		int idx = changeUnitList.getSelectedIndex();
		if(idx < 0)
			return;
		changeUnits.remove(idx);
		changeUnitList.repaint();
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new NewChangeUnitForm_ColumnList().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify
	private javax.swing.JButton Deselect;
	private javax.swing.JButton Select;
	private javax.swing.JList changeUnitList;
	private javax.swing.JButton createChangeUnit;
	private javax.swing.JButton deleteChangeUnit;
	private javax.swing.JButton doneButton;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JScrollPane jScrollPane4;
	private java.awt.List selectedList;
	private java.awt.List unselectedList;
	// End of variables declaration

}
